<template>
  <el-container>
    <!-- 固定在顶部的header -->
    <el-header class="customHeader fixed-header">
      <div class="topBar"></div>
      <div class="headerContent">
        <!-- 左侧：Logo + 分隔线 + 标题 -->
        <div class="headerLeft">
          <img src="../assets/image/logo.jpg" class="logo" @click="$router.push('/')" />
          <div class="headerDivider"></div>
          <div class="titleWrapper">
            <div class="mainTitle">讯航<span class="newsText">News</span></div>
            <div class="subTitle">——武大新闻整合平台</div>
          </div>
        </div>

        <div class="headerRightGroup">
          <!-- 右侧：搜索框 -->
          <div class="headerRight">
            <el-input
              v-model="searchText"
              placeholder="文章搜索"
              class="searchInput"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button class="custom-search-btn" @click="handleSearch">
                  <img src="../assets/image/搜索.png" class="search-icon" alt="搜索" />
                </el-button>
              </template>
            </el-input>
          </div>
        </div>
      </div>
    </el-header>

    <!-- 添加占位元素避免内容被遮挡 -->
    <div class="header-placeholder"></div>

    <el-main>
      <!-- 第二部分：顶部功能区 -->
      <div class="top-function-area">
        <div class="sortContent">
          <div class="sortButtons">
            <span class="sortLabel">排序：</span>
            <el-button
              type="primary"
              size="large"
              class="sortBtn sortTime"
              @click="toggleTimeSort"
            >
              时间排序 {{ timeSortDirection === 'asc' ? '(升序)' : '(降序)' }}
            </el-button>

            <el-button
              type="primary"
              size="large"
              class="sortBtn sort-watch"
              @click="handleSortByWatch"
            >
              按浏览量排序
            </el-button>

            <!-- 时间范围选择器 -->
            <el-date-picker
              v-model="timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleTimeRangeChange"
              :clearable="true"
            />
          </div>
          <hr />
        </div>
      </div>

      <!-- 第三部分：中间内容区 -->
      <div class="middle-content-area">
        <!-- 左侧20%：分类栏 -->
        <div class="category-sidebar">
          <div class="category-card">
            <el-menu 
              class="category-menu" 
              @select="handleCategorySelect"
              :default-active="currentCategory.toString()"
            >
              <el-menu-item index="1">
                <span class="category-item">武大咨询</span>
              </el-menu-item>
              <el-menu-item index="2">
                <span class="category-item">珞珈人物</span>
              </el-menu-item>
              <el-menu-item index="3">
                <span class="category-item">信息发布</span>
              </el-menu-item>
              <el-menu-item index="4">
                <span class="category-item">校园生活</span>
              </el-menu-item>
            </el-menu>
          </div>
        </div>

        <!-- 右侧80%新闻卡片容器 -->
        <div class="newsContainer">
          <!-- 加载状态 -->
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="5" animated />
          </div>

          <!-- 新闻卡片 -->
          <template v-else>
            <div 
              v-for="item in newsData"
              :key="item.id"
              class="newsCard"
            >
              <div class="newsImage">
                <img :src="item.images || defaultImage" class="image" />
              </div>
              <div class="newsContent">
                <h3 class="title">{{ item.title }}</h3>
                <p class="summary">{{ item.detail }}</p>
                <div class="meta">
                  <span class="date">{{ formatDate(item.submittime) }}</span>
                  <span class="views">浏览: {{ item.pageviews }}次</span>
                  <el-tag :type="getTagType(item.typeId)">
                    {{ getCategoryName(item.typeId) }}
                  </el-tag>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-if="!newsData.length" class="no-data">
              <el-empty description="暂无新闻数据" />
            </div>
          </template>
        </div>
      </div>

      <!-- 第四部分：页脚分页 -->
      <div class="footerPagination">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total * pageSize"
          :page-count="total"
          layout="prev, pager, next, jumper"
          @current-change="handlePageChange"
          :disabled="loading"
        />
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 常量定义
const API_BASE = 'http://localhost:8080/news/type'
const defaultImage = '../assets/image/logo.jpg'

// 响应式数据
const currentCategory = ref(1)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const newsData = ref([])
const loading = ref(false)
const timeSortDirection = ref('desc')
const timeRange = ref([])
const searchText = ref('')

// 分类映射
const categoryMap = {
  1: '武大咨询',
  2: '珞珈人物',
  3: '信息发布',
  4: '校园生活'
}

// 标签类型映射
const tagTypeMap = {
  1: 'success',
  2: 'warning',
  3: 'info',
  4: 'danger'
}

// 获取分类名称
const getCategoryName = (typeId) => {
  return categoryMap[typeId] || '未知分类'
}

// 获取标签类型
const getTagType = (typeId) => {
  return tagTypeMap[typeId] || ''
}

// 格式化日期
const formatDate = (dateString) => {
  return dateString ? dateString.replace('T', ' ').substring(0, 19) : ''
}

// 获取新闻数据
const fetchNewsData = async () => {
  loading.value = true
  try {
    const params = {
      tid: currentCategory.value,
      current: currentPage.value
    }

    // 添加时间参数
    if (timeRange.value && timeRange.value.length === 2) {
      params.previousTime = timeRange.value[0]
      params.followingTime = timeRange.value[1]
    }

    // 添加排序参数
    params.order = timeSortDirection.value === 'desc' ? 'desc' : 'asc'

    const response = await axios.get(API_BASE, { params })
    
    if (response.data.success) {
      newsData.value = response.data.data || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.data.erroring || '获取数据失败')
    }
  } catch (error) {
    ElMessage.error('请求失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 分类切换
const handleCategorySelect = (tid) => {
  currentCategory.value = Number(tid)
  currentPage.value = 1
  fetchNewsData()
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchNewsData()
}

// 时间排序切换
const toggleTimeSort = () => {
  timeSortDirection.value = timeSortDirection.value === 'desc' ? 'asc' : 'desc'
  fetchNewsData()
}

// 时间范围变化
const handleTimeRangeChange = () => {
  currentPage.value = 1
  fetchNewsData()
}

// 搜索处理
const handleSearch = () => {
  if (searchText.value.trim()) {
    ElMessage.info('搜索功能: ' + searchText.value.trim())
  } else {
    ElMessage.warning('请输入搜索内容')
  }
}

// 初始化加载
onMounted(() => {
  fetchNewsData()
})
</script>

<style scoped>

/* 新增样式 */
.loading-container {
  padding: 20px;
}

.no-data {
  padding: 40px 0;
  text-align: center;
}

/* 调整现有样式 */
.newsCard {
  /* 确保图片不会变形 */
  .newsImage img {
    width: 100%;
    height: 180px;
    object-fit: cover;
  }
  
  .newsContent {
    .summary {
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
  }
}
.date-filter-group {
  display: flex;
  align-items: center;
  margin-right: 0.625rem;
  vertical-align: middle; /* 确保与其他行内元素对齐 */
}

.date-range-picker {
  width: 17.5rem;
  margin: 0 0.625rem 0 0; /* 只保留右边距 */
  height: 2.5rem; /* 与按钮高度保持一致 */
}

.reset-date-filter {
  margin-left: 0.3125rem;
}

/* 使日期选择器和按钮在同一行对齐 */
.el-date-editor.el-input, .el-date-editor.el-input__inner {
  width: 100%;
}

/* 调整Element默认样式 */
.el-date-editor .el-range-separator {
  padding: 0 0.5rem; /* 调整分隔符间距 */
}

/* 中间内容区布局 */
.middle-content-area {
  display: flex;
  margin-top: 1.25rem;
}

/* 左侧分类栏 */
.category-sidebar {
  width: 20%;
  padding-right: 1.25rem;
}

.category-card {
  background: #fff;
  border-radius: 0.5rem;
  box-shadow: 0 0.125rem 0.75rem 0 rgba(0, 0, 0, 0.1);
  padding: 0.9375rem;
}

.category-title {
  font-size: 1.125rem;
  font-weight: bold;
  margin-bottom: 0.9375rem;
  color: #333;
}

.category-menu {
  border-right: none;
}

.category-item {
  font-size: 1rem;
  padding: 0.75rem 1.25rem !important;
  border-radius: 10%;
}

.el-menu-item.is-active {
  background-color: #f5f7fa;
  color: #409eff;
  font-weight: bold;
}
/* 右侧新闻内容区 */
.news-main-content {
  width: 80%;
}

/*

-----整体样式-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

 */

body {
  margin: 0;
  padding: 0;
}

:deep(.el-container) {
  padding: 0 !important;
  margin: 0 !important;
}

.el-main {
  padding: 0 0.625rem; /* 保留少量内边距 */
  max-width: 100%;
}

.banner-image img {
  display: block; /* 移除图片底部间隙 */
}

/*

-----header样式-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

 */

.topBar {
  height: 1.875rem;
  width: 100%;
  background-color: #b6daff;
}

/* 固定头部样式 */
.fixed-header {
  position: fixed !important;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000; /* 确保在最上层 */
  width: 100% !important;
}

/* 占位元素样式 (根据您实际的header高度调整) */
.header-placeholder {
  height: 8.125rem; /* topBar(1.875rem) + headerContent(6.25rem) */
}

/* 标题区域样式 */
.customHeader {
  background-color: #ffffff; /* 背景眼色 */
  color: rgb(7, 0, 0); /* 文字颜色 */
  padding: 0 1.25rem;
  height: 7.5rem;
  display: flex;
  align-items: center;
  flex-direction: column; /* 改为垂直布局 */

  transform: translateY(-0.125rem); /* 向上浮动一点点 */
  box-shadow:
    0 0.25rem 0.5rem rgba(0, 0, 0, 0.1),
    0 0.5rem 1rem rgba(0, 0, 0, 0.1),
    0 0.75rem 1.5rem rgba(0, 0, 0, 0.1); /* 多层叠加阴影，营造立体感 */
  position: relative; /* 确保阴影可见 */
  z-index: 1000; /* 保持悬浮层级 */
}


/* 标题内容样式 */
.headerContent {
  width: 100%;
  display: flex;
  justify-content: space-between; /* 改为左右布局 */
  align-items: center;
}

/* logo样式 */
.logo {
  height: 5rem;
  width: auto;
  object-fit: contain;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
}

.logo:hover {
  transform: translateY(-0.1875rem) scale(1.03);
  box-shadow: 0 0.625rem 1.25rem rgba(0, 0, 0, 0.1);
}

/* 标题容器 */
.titleWrapper {
  display: flex;
  flex-direction: column;
}

/* 主标题样式 */
.mainTitle {
  font-size: 2.5rem;
  font-weight: bold;
  color: #000;
}

/* News文字样式 */
.newsText {
  margin-left: 0.3125rem;
}

/* 副标题样式 */
.subTitle {
  font-size: 1.25rem;
  color: #409eff; /* Element Plus 主蓝色 */
}

/* 分割线 */
.headerDivider {
  height: 5rem;
  width: 0.0625rem;
  background-color: #c9d5f1;
}

/* 新增左侧容器 */
.headerLeft {
  display: flex;
  align-items: center;
  gap: 0.9375rem;
}

/* 右侧搜索框样式 */
.headerRight {
  width: 17.5rem;
  margin-left: auto;
}

/* 输入框样式 */
.searchInput {
  :deep(.el-input__inner) {
    height: 2.5rem;
    line-height: 2.5rem;
    font-size: 1rem;
    padding: 0 0.9375rem;
    /* 确保输入区域可点击 */
    pointer-events: auto;
    cursor: text;
  }

  :deep(.el-input__wrapper) {
    /* 移除可能遮挡的样式 */
    overflow: visible;
  }
}

.search-icon {
  width: 1.25rem;
  height: 1.25rem;
  object-fit: contain;
}

.headerRightGroup {
  display: flex;
  align-items: center;
  gap: 1.25rem;
}

/*

-----排序区域样式-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

 */

/* 添加热门按钮激活状态样式 */
.sortHot.is-active {
  background: var(--el-color-danger) !important;
  border-color: var(--el-color-danger) !important;
  color: white !important;
}

.sortTime {
  /* 添加过渡效果 */
  transition: all 0.3s ease;
  
  /* 当前激活状态 */
  &.active {
    background-color: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary);
  }
}
 
/* 排序按钮区域样式 */
.sortButtons {
  display: flex;
  flex-wrap: wrap;
  align-items: center; /* 垂直居中 */
  gap: 0.3125rem;
  margin-bottom: 1.25rem;
}

/* "排序："文字样式 */
.sortLabelone {
  font-size: 1.125rem;
  color: #606266;
  margin-top: 1.875rem;
  margin-right: 0.625rem; /* 文字和按钮间距 */
  margin-bottom: 0rem;
  white-space: nowrap; /* 防止文字换行 */
}

/* "按日期筛选："文字样式 */
.sortLabel {
  font-size: 1rem;
  color: #606266;
  margin: 0.3125rem;
  white-space: nowrap; /* 防止文字换行 */
}

/* 统一的基础按钮样式 */
.sortBtn,
.sortBtnbyDateRange {
  display: inline-flex; /* 使用inline-flex保持行内特性 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  height: 2.5rem; /* 固定高度 */
  padding: 0 1.25rem; /* 左右内边距 */
  margin: 0rem 0.625rem 0 0; /* 只保留右边距 */
  font-size: 1rem; /* 统一字号 */
  line-height: 1; /* 重置行高 */
  border-radius: 0.25rem; /* 圆角统一 */
  background: white !important;
  border: 0.0625rem solid #dcdfe6 !important;
  color: #606266 !important;
  transition: all 0.3s ease;
  white-space: nowrap; /* 防止文字换行 */
}

/* 悬停状态 */
.sortBtn:hover,
.sortBtnbyDateRange:hover {
  background: #409eff !important;
  border-color: #409eff !important;
  color: white !important;
}

/* 特定按钮的微调 */
.sortBtnbyDateRange {
  margin-left: 0.625rem; /* 适当缩小左边距 */
}

/* 可选：按钮激活状态样式（点击后保持蓝色） */
.sortBtn.is-active {
  background: #409eff !important;
  border-color: #409eff !important;
  color: white !important;
}

/*

-----新闻卡片样式-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

 */

.date {
    font-size: 1.125rem;
}

.views {
    font-size: 0.8125rem;
}

.batch-controls {
    margin-left: 20%;
}

/* 新闻卡片样式 */


.newsContainer {
  width: 90%;
  margin: 0 auto;
  padding: 1.25rem;
}

.newsCard {
  margin-bottom: 1.25rem; /* 增加卡片间距 */
  transition: all 0.3s; /* 添加悬停动画 */
  display: flex;
  width: 100%;
  border: 0.0625rem solid #ebeef5;
  border-radius: 0.25rem;
  overflow: hidden;
  background: #fff;
  position: relative;
}

.newsCard:hover {
  box-shadow: 0 0.125rem 0.75rem rgba(0, 0, 0, 0.1);
  transform: translateY(-0.1875rem);
}

.newsImage {
  flex: 0 0 7.5rem; /* 固定宽度 */
  padding: 0.625rem;
  display: flex;
  align-items: center;
}

.image {
  width: 100%;
  height: 5rem; /* 固定高度 */
  object-fit: cover; /* 保持图片比例 */
}

.newsImage {
  flex: 0 0 20%;
}

.image {
  width: 70%;
  height: auto;
  object-fit: contain; /* 保持比例 */
}

.newsContent {
  flex: 0 0 80%;
  padding: 0.9375rem;
}

.title {
  font-size: 1.125rem;
  margin: 0 0 0.625rem 0;
  color: #303133;
}

.summary {
  font-size: 0.875rem;
  color: #606266;
  line-height: 1.6;
  margin: 0 0 0.625rem 0;
}

/* 日期区域 */
.meta {
  font-size: 0.75rem;
  color: #909399;
}

/*

-----页脚样式-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
 */

.footerPagination {
  position: fixed;
  bottom: 1.25rem;
  left: 0;
  right: 0;
  background: #fff;
  padding: 0.9375rem 0;
  display: flex;
  justify-content: center;
  box-shadow: 0 -0.125rem 0.625rem rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.el-pagination {
  --el-pagination-font-size: 1.125rem !important;
}

.el-main {
  padding-bottom: 5rem !important; /* 等于或大于页脚高度 */
}
</style>
